<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh">
	<head>
		<meta charset="UTF-8">
		<title>Document</title>
		<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
		<!-- Font Awesome 图标 -->
		<link rel="stylesheet" href="fontawesome/css/all.min.css">
		<link rel="stylesheet" href="css/base.css" />
		<link rel="stylesheet" href="css/buyGoods.css" />
	</head>
	<body>
		<div class="modal fade" id="orderSuccessModal1" tabindex="-1" aria-labelledby="orderSuccessModalLabel1" aria-hidden="true">
    		<div class="modal-dialog">
        		<div class="modal-content">
            		<div class="modal-header">
                		<h5 class="modal-title" id="orderSuccessModalLabel1">下单成功</h5>
                		<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            		</div>
            		<div class="modal-body text-center">
                		<i class="fas fa-check-circle text-success" style="font-size: 3rem;"></i>
                		<p class="mt-3">您的订单已成功提交！</p>
            		</div>
            		<div class="modal-footer">
                		<button type="button" class="btn btn-primary" data-bs-dismiss="modal" onclick="window.location.href='order.jsp'">确定</button>
            		</div>
        		</div>
    		</div>
		</div>
		<div class="modal fade" id="orderSuccessModal2" tabindex="-1" aria-labelledby="orderSuccessModalLabel2" aria-hidden="true">
    		<div class="modal-dialog">
        		<div class="modal-content">
            		<div class="modal-header">
                		<h5 class="modal-title" id="orderSuccessModalLabel2">下单失败</h5>
                		<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            		</div>
            		<div class="modal-body text-center">
                		<i class="fas fa-times-circle text-danger" style="font-size: 3rem;"></i>
                		<p class="mt-3">提交失败！请选择地址！</p>
            		</div>
            		<div class="modal-footer">
                		<button type="button" class="btn btn-primary" data-bs-dismiss="modal">确定</button>
            		</div>
        		</div>
    		</div>
		</div>
		<!-- 导航栏 -->
		<div class="container-fluid fixed-top  navbar-custom" id="top">
			<nav class="navbar navbar-expand-lg" role="navigation">

				<div class="container">
					<a href="index.jsp" class="navbar-brand navbar-b-custom font-logo">
						<img src="img/headLogo.png" alt="" id="headImage">
					</a>
					<!-- 搜索条 -->
					<form action="searchGoodsDo" method="get">
						<div class="d-flex position-absolute start-50 translate-middle-x serchBar">
							<input name="searchName" type="text" class="form-control form-control-sm" id="searchBar" />
							<button class="btn btn-primary ms-2 serchBut" id="searchBtn">搜索</button>
						</div>
					</form>
					<!-- 右侧用户信息栏 -->
					<ul class="navbar-nav mb-2 mb-lg-0 align-items-center">
						<c:choose>
        				<c:when test="${not empty sessionScope.logInUser}">
            				<ul class="navbar-nav mb-2 mb-lg-0 align-items-center">
								<li class="nav-item d-flex align-items-center">
									<img src="${logInUser.headimg}" alt="" class="headimg align-self-center">
								</li>
								<li class="nav-item"><a href="mineInformation.jsp" class="nav-link navbar-a-custom" id="">个人主页</a></li>
								<li class="nav-item"><a href="order.jsp" class="nav-link navbar-a-custom">我的订单</a></li>
								<!-- <li class="nav-item"><a href="" class="nav-link navbar-a-custom">我的好物</a></li> -->
							</ul>
        				</c:when>
        				<c:otherwise>
            				<ul class="navbar-nav mb-2 mb-lg-0 align-items-center">
								<li class="nav-item"><a href="#" class="nav-link navbar-a-custom" id="sign">注册</a></li>
								<li class="nav-item"><a href="#" class="nav-link navbar-a-custom" id="login">登录</a></li>
							</ul>
        				</c:otherwise>
    				</c:choose>
					</ul>
				</div>
			</nav>
		</div>
		<!-- 中部信息区 -->
		<div class="container-fluid" id="middle">
			<div class="container middle">
				<div style="display: inline-block;width: 70%;">
					<div class="address">
						<p><strong>收货地址</strong></p>
						<p class="type">
							<input type="radio" name="tradeType" id="" class="tradeType" value="type1" checked>邮寄
							<input type="radio" name="tradeType" id="" class="tradeType" value="type2">自提
						</p>
						<div class="container-fluid address_show">
							<div class="adds">
            					<ul class="row narrow-and-fade-back row_custom"
								style="list-style: none;padding-left: 0px;">
									<c:forEach items="${address}" var="add" varStatus="status">
    									<li class="col-md-3">
											<div class="address_info">
												<p>
													<input type="hidden" value="${add.addressid }">
													<i class="fa fa-map-marker"></i>
													<small>${add.province }${add.city }${add.site }</small>
												</p>
												<p><strong>${add.other }</strong></p>
												<p><small>${add.name } ${add.phoneNum }</small></p>
											</div>
										</li>
									</c:forEach>
								</ul>
							</div>
						</div>
					</div>
					<div class="goods">
						<p><strong>商品信息</strong></p>
						<div class="goods-info">
							<img src=${goods.goodimg } alt="" />
							<div class="goods-info-text">
								<p>${goods.goodname }</p>
								<p>￥${goods.goodprice }</p>
							</div>
						</div>
						<p><strong>商品数量</strong></p>
						<div class="quantity-selector">
							<button class="btn btn-outline-secondary minus-btn" type="button">-</button>
							<input id="goodNum" type="number" class="form-control quantity-input" value="1" min="1" max="99">
							<button class="btn btn-outline-secondary plus-btn" type="button">+</button>
						</div>
					</div>
				</div>
				<div class="pay">
					<p><strong>商品总价</strong></p>
					<p><span style="font-size: 15px;"><strong>总价：</strong></span><span>￥${goods.goodprice }</span></p>
					<p>运费：<small>￥0</small></p>
					<hr>
					<p>合计：</p>
					<p><span style="font-size: 25px;color: red;" id="allPrice">￥${goods.goodprice }</span></p>
					<p class="text-center"><button id="buyNow">确认下单</button></p>
				</div>
			</div>
		</div>

		<!-- 底部区 -->
		<footer class="container-fluid bottom p-3 mt-auto" id="footer">
			<div class="font-logo infoLeft mx-auto">
				<strong>复焕集 </strong>旧物也能焕然一新的二手市场。
			</div>
			<div class="container">
				<div class="d-flex flex-wrap justify-content-between">
					<ul class="footer-links mb-2 mb-lg-0 flex-grow-1 px-3 text-center">
						<strong>关于我们</strong>
						<li><a href="">公司介绍</a></li>
						<li><a href="">团队介绍</a></li>
						<li><a href="">媒体报道</a></li>
						<li><a href="">加入我们</a></li>
					</ul>
					<ul class="footer-links mb-2 mb-lg-0 flex-grow-1 px-3 text-center">
						<strong>帮助中心</strong>
						<li><a href="">新手入门</a></li>
						<li><a href="">交易流程</a></li>
						<li><a href="">常见问题</a></li>
						<li><a href="">安全指南</a></li>
					</ul>
					<ul class="footer-links mb-2 mb-lg-0 flex-grow-1 px-3 text-center">
						<strong>规则中心</strong>
						<li><a href="">用户协议</a></li>
						<li><a href="">隐私政策</a></li>
						<li><a href="">交易规则</a></li>
						<li><a href="">社区公约</a></li>
					</ul>
					<ul class="footer-links mb-2 mb-lg-0 flex-grow-1 px-3 text-center">
						<strong>联系我们</strong>
						<li><a href="">客服电话：400-114-514</a></li>
						<li><a href="">商务合作：bd@fuhuanji.com</a></li>
						<li><a href="">举报反馈：report@fuhuanji.com</a></li>
					</ul>
				</div>
			</div>
		</footer>
	</body>
	<script src="bootstrap/js/bootstrap.min.js"></script>
	<script src="js/jquery.js"></script>
	<!-- <script src="js/buyGoods.js"></script>-->
	<script>
	$(window).on('load', function() {
		var buyerAddressid = 0;
		var allPrice = ${goods.goodprice }
		var goodNum = $('#goodNum').val();
		var sellerAddress = null;
		var buyerAddress = null;
		var type = "type1";
		const maxNum = ${goods.goodnum}
		console.log("存量："+maxNum)
		$('#buyNow').click(function(){
			if(type == "type1"){
				if(buyerAddressid == 0){
					var orderSuccessModal = new bootstrap.Modal(document.getElementById('orderSuccessModal2'));
	                orderSuccessModal.show();
				}else{
					$.ajax({
						url: "buyDo",
						type: 'get',
						data: {
							allPrice:allPrice,
							goodNum:goodNum,
							buyerAddressid:buyerAddressid
						},
						success:function(){
							console.log('成功')
							var orderSuccessModal = new bootstrap.Modal(document.getElementById('orderSuccessModal1'));
			                orderSuccessModal.show();
						},
						error: function(xhr, status, error) {
							
							console.log('Error:', status, error);
							console.log("原始响应:", xhr.responseText);  // 这里会显示服务器返回的真实内容
						    console.log("状态码:", xhr.status);
						}
					})
				}
			}else{
				$.ajax({
					url: "buyDo",
					type: 'get',
					data: {
						allPrice:allPrice,
						goodNum:goodNum,
						buyerAddressid:0
					},
					success:function(){
						console.log('成功')
						var orderSuccessModal = new bootstrap.Modal(document.getElementById('orderSuccessModal1'));
		                orderSuccessModal.show();
					},
					error: function(xhr, status, error) {
						console.log('Error:', status, error);
						console.log("原始响应:", xhr.responseText);  // 这里会显示服务器返回的真实内容
					    console.log("状态码:", xhr.status);
					}
				})
			}
			
		})
		$(".tradeType").click(function(){
			if($(this).val() == "type2"){
				type = "type2";
				$('.adds').empty();
				$('.adds').append('<p class="text-center" style="width:100%;color:rgba(0, 0, 0, 0.2);">自提请与商家沟通，确认交易地点与交易时间！</p>')
				$('.pay').find('p').eq(2).children().text("自提")
			}else {
				type = "type1";
				$('.adds').empty();
				var things = `
					<ul class="row narrow-and-fade-back row_custom"
					style="list-style: none;padding-left: 0px;">
						<c:forEach items="${address}" var="add" varStatus="status">
							<li class="col-md-3">
								<div class="address_info">
									<p>
										<i class="fa fa-map-marker"></i>
											<small>${add.province }${add.city }${add.site }</small>
									</p>
									<p><strong>${add.other }</strong></p>
									<p><small>${add.name } ${add.phoneNum }</small></p>
								</div>
							</li>
						</c:forEach>
					</ul>
				`
				$('.adds').append(things)
			}
		})
		$('.row_custom').on('click','.address_info',function(){
			$('.clicked').removeClass('clicked')
			$(this).addClass('clicked')
			sellerAddress = '${goods.seller.address}';
			buyerAddress = $(this).find('p:first-of-type small').text()
			var feeType = '${goods.goodFreightType}'
			buyerAddressid = $(this).find('input').val();
			console.log("地址id为："+buyerAddressid)
			$.ajax({
				url: "buyGoods",
				type: 'POST',
				data: {
					address1:sellerAddress,
					address2:buyerAddress,
					goodNum:goodNum
				},
				success:function(data){
					console.log('成功')
					if(feeType == '卖家包邮'){
						$('.pay').find('p').eq(2).children().text("卖家包邮")
						$('#allPrice').text("￥"+allPrice.toFixed(2))
					}else{
						console.log(data)
						$('.pay').find('p').eq(2).children().text("￥"+data)
						allPrice += data
						$('#allPrice').text("￥"+allPrice.toFixed(2))
					}
				},
				dataType:'json'
			})
		})
		document.querySelectorAll('.quantity-selector').forEach(function(selector) {
			const minusBtn = selector.querySelector('.minus-btn');
			const plusBtn = selector.querySelector('.plus-btn');
			const input = selector.querySelector('.quantity-input');
			function showStockWarning() {
                // 如果提示元素已存在则先移除
                if ($('.stock-warning').length) {
                    $('.stock-warning').remove();
                }
                
                // 创建提示元素
                const warning = $('<div class="stock-warning text-danger small mt-2">购买数量不能超过存量</div>');
                $(selector).after(warning);
                
                // 3秒后自动消失
                setTimeout(() => {
                    warning.fadeOut(500, () => warning.remove());
                }, 3000);
            }
			minusBtn.addEventListener('click', function() {
				let value = parseInt(input.value);
				if (value >= parseInt(input.min)) {
					if(value != 1){
						input.value = value - 1;
					}
				}
			});

			plusBtn.addEventListener('click', function() {
				let value = parseInt(input.value);
				if (value < parseInt(input.max)) {
					if(value >= maxNum){
						input.value = value
						showStockWarning()
					}else{
						input.value = value + 1;
					}
				}
			});

			// 手动输入时的验证
			input.addEventListener('change', function() {
                let value = parseInt(this.value);
                if (isNaN(value) || value < parseInt(this.min)) {
                    this.value = this.min;
                } else if (value > parseInt(this.max)) {
                    this.value = this.max;
                    showStockWarning();
                } else if (value > maxNum) {
                    this.value = maxNum;
                    showStockWarning();
                }
            });
		});
	})
		document.addEventListener('DOMContentLoaded', function() {
			
		});
	</script>
</html>